<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c"%>
<%@ taglib uri="/WEB-INF/tld/ui.tld" prefix="ui"%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="renderer" content="webkit">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>追加费用</title>
<jsp:include page="../../import.jsp" flush="true" />
</head>
<style>
.error{
	color:red;
}
</style>
<body class="iframeBody">
	<div class="Wrapper">
		<div id="pageInTab" class="pageInTab">
			<form id="addition_charges_form" class="l-form">
				<div class="fieldset1 tabel_col tabel_col_s clearFix">
					<div class="caption">
						<span class="title">追加费用 </span>
						<div style="margin-left: auto;margin-right: 10px;width:200px;margin-top: -15px">
							<span id="scm_cost2_sv_btn_id"
								class="sq-button sq-button-round" onclick="addNewGrade();">新增
							</span>
							<span id="scm_cost2_del_btn_id"
								class="sq-button sq-button-round" onclick="delGrade();" >删除选中行
							</span>
						</div>
					</div>
					<div class="fieldBox col_100">
							<div id="gradeDateId" class="sq-grid"></div>
					</div>
				</div>
				<div class="btnsBox" >
					<span id="add_btn_id" class="sq-button sq-button-round" >保存并发起流程</span>
				</div>
			</form>
		</div>
		
		<div class="fieldBox col_100" style="display:none;">
	        	<input id="paySchId" type="text" class="ui-textbox" value="${paySchId}">
	        	<input id="paySchNo" type="text" class="ui-textbox" value="${paySchNo}">
	    </div>
	</div>
	<script type="text/javascript">
		var docArray ={};
	    var griddata ;
		var paySchId = '${paySchId}';
		var paySchNo = '${paySchNo}';
	    // 验证值小数位数不能超过指定位数param 
	    $.validator.addMethod("decimallen", function(value, element, param) {
	        var decimallen =eval("/^-?\\d+(\\.\\d{0," + param + "})?$/"); 
	        return this.optional(element) || (decimallen.test(value));
		}, "小数位数不能超过{0}位");
	    
		$(function () {
			initChargesData();
        	$("#addition_charges_form").ligerForm({
        		validate:true
            });
			saveBtnEvent();
		});
		
		
	    function initChargesData()
	    { 
			var paySchNo = $("#paySchNo").val();
			griddata = $("#gradeDateId").ligerGrid({
			    	url: '<%=path%>/project/prjprdpayschm/initAdditionalCharges.do',
			    	method : 'post',
			    	parms:{"paySchNo":paySchNo},
	                columns: [
	                	{ display: '编号', name: 'id',width: 150,type: 'text' },
		                { display: '费用项',  name: 'feeTypeCd',width: 150,type:'text', 
		                	editor: { type: 'select', 
								data: [
									{ value: '过户提档费', key: '1' },
									{ value: '停车费', key: '2' },
									{ value: '其他费用', key: '3' },
									{ value: '拖车费', key: '4' },
									{ value: '运费', key: '5' },
									{ value: '整备费', key: '6' }
				                ],
								valueField: 'key', textField: 'value' },
								render: function (item)
			                    {
			                        if (parseInt(item.feeTypeCd) == 1) return '过户提档费';
			                        if (parseInt(item.feeTypeCd) == 2) return '停车费';
			                        if (parseInt(item.feeTypeCd) == 3) return '其他费用';
			                        if (parseInt(item.feeTypeCd) == 4) return '拖车费';
			                        if (parseInt(item.feeTypeCd) == 5) return '运费';
			                        if (parseInt(item.feeTypeCd) == 6) return '整备费';
			                    }
		                },
		                { display: '借款金额',  name: 'applyAmt',width: 150,type:'float', editor: { type: 'float' }},
	               	    { display: '开户行', name: 'payeeBankNm',width: 150,type: 'text', editor: { type: 'text'} },
	               	    { display: '开户行行号', name: 'payeeBankNo',width: 150,type: 'text', editor: { type: 'text'} },
	               		{ display: '收款账号', name: 'payeeAccNo',width: 150,type: 'text', editor: { type: 'text'} },
	               		{ display: '收款户名', name: 'payeeAccNm',width: 150,type: 'text', editor: { type: 'text'} },
	               		{ display: '用途备注', name: 'feeDesc',width: 150,type: 'text', editor: { type: 'text'} },
	               		{ display: '附件上传', name: 'fileUploader',width: 150,isSort: false,isEllipsis: false, 
	               			render: function (rowdata, rowindex, value){
	               				var str =  '<a class="sq-button-hasicon" id="btn_'+rowdata.id+'" href="javascript:addFileRes(';
	               					str += "'"+rowdata.id+"'";
	               					str += ')"><i class="sqBtnIco_3" ></i>上传附件</a>';
	               				return str;
	               			}
	               		}
						],
		                
		                onSelectRow: function (rowdata, rowindex)
		                {
		                    $("#txtrowindex").val(rowindex);
		                },
		                enabledEdit: true, isScroll: false, 
		                width: '100%',
		    	        root:'Rows',
		    	        record:'Total',
		    	        hideLoadButton : true,
		    	        width: '100%',
		    	        height:'100%',
		    	        heightDiff:-2,
		    	        checkbox:true,
		    	        rownumbers:true
		            }); 	   	
		}

        function delGrade()
        { 	
        	//删除附件变量中的信息
        	var selectGriddatas = griddata.getSelectedRows();//selecteds
        	for(var i=0;i<selectGriddatas.length;i++){
        		var id = selectGriddatas[i].id+"";
        		delete docArray[id];
        	}
        	griddata.deleteSelectedRow();
        }   
		
        function addNewGrade()
        {
        	//生成主键id 
        	$.ajax({
           	   type: "post",
           	   url: "<%=path%>/ass/assSchFee/getId.do",
           	   contentType: 'application/json',
           	   data: "",
           	   dataType:"json",
           	   success: function(result){
           		   	var id = result.id;
           		   	if(id==0){
	           		   	$.ligerDialog.SQalert({content:"内部序列化错误!",SQ_type: "error"});
	                	return;
           		   	}
           			griddata.addRow({"id":id});
           			// 添加附件的需要取消按钮事件
           		    var allGriddatas = griddata.getData();
           			for(var i=0;i<allGriddatas.length;i++){
                        var id = allGriddatas[i].id+"";
                        if(docArray[id] != null ){
                        	$("#btn_"+id).removeAttr('href');
                        }
                    }
           	   }
           	});
        } 
		
    	//格式化时间
    	function renderDate(rowdata, index, value){
    		var dateStr = "";
    		if(null != value){
    			var date = new Date(value);
    			dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DD);
    		}
    		return dateStr;
    	}
        
        
        //保存事件
        function saveBtnEvent(){
        	$("#add_btn_id").click(function(event) {
                var form = liger.get("addition_charges_form");
                var paySchId = $("#paySchId").val();
                var paySchNo = $("#paySchNo").val().toString();
                //获取附件信息
				//alert("最后得数据    :   "+JSON.stringify(docArray));
                // 校验数据是否格式是否正确
                var dataList = griddata.getData();
                for(var i=0;i<dataList.length;i++){
                	//判断费用项是否为空
        			if(!dataList[i].feeTypeCd){
        				$.ligerDialog.SQalert({content: "请选择 费用项！",SQ_type: "warning"});
        				return false;
        			}
        			if(!dataList[i].applyAmt){
        				$.ligerDialog.SQalert({content: "请填写 借款金额！",SQ_type: "warning"});
        				return false;
        			}
        			if(!dataList[i].payeeBankNm){
        				$.ligerDialog.SQalert({content: "请填写 开户行！",SQ_type: "warning"});
        				return false;
        			}
        			if(!dataList[i].payeeBankNo){
        				$.ligerDialog.SQalert({content: "请填写 开户行行号！",SQ_type: "warning"});
        				return false;
        			}
        			if(!/^[0-9]*$/.test(dataList[i].payeeBankNo)){
        				$.ligerDialog.SQalert({content: "开户行行号  格式不正确 ！",SQ_type: "warning"});
        				return false;
        			}
        			if(!dataList[i].payeeAccNo){
        				$.ligerDialog.SQalert({content: "请填写 收款账号！",SQ_type: "warning"});
        				return false;
        			}
        			if(!/^[0-9]*$/.test(dataList[i].payeeAccNo)){
        				$.ligerDialog.SQalert({content: "收款账号  格式不正确 ！",SQ_type: "warning"});
        				return false;
        			}
        			if(!dataList[i].payeeAccNm){
        				$.ligerDialog.SQalert({content: "请填写 收款户名！",SQ_type: "warning"});
        				return false;
        			}
                }
                // 校验附件是否存在
                if(Object.keys(docArray).length != dataList.length){
                	$.ligerDialog.SQalert({content: "还有记录未添加附件！",SQ_type: "warning"});
    				return false;
                }
                var jsondata = "{\"paySchId\":"+paySchId+",\"paySchNo\":\""+paySchNo+"\",\"gradeDate\":"+JSON.stringify(griddata.getData())+",\"docArray\":["+JSON.stringify(docArray)+"]}";
                if(griddata.getData().length==0){
                	$.ligerDialog.SQalert({content:"请添加需要追加得费用项 !",SQ_type: "warning"});
                	return;
                }
                $.ligerDialog.confirm("确定要保存并发起追加费用流程吗？", function (flag) {
					if(flag == false)return;
	                $.ajax({
	             	   type: "POST",
	             	   url: "<%=path%>/ass/assSchFee/saveAssSchFeeD.do",
	             	   contentType: 'application/json',
	             	   data: JSON.stringify(jsondata),
	             	   dataType:"json",
	             	   success: function(data){
	             	   		if("1"==data.resultType){// 添加成功以后需要跳转到费用明细
	             	   	       // 父页面回掉函数 callback()
		             	   		var TAB = top.mainApp.parentTab;
		             	        var currentTabid = TAB.getSelectedTabItemID();
		             	        var currentTabiframe = top.$("#"+currentTabid).get(0);
		             	        var callback = currentTabiframe.W2W.callback;
		             	        callback();
	             	   			$.ligerDialog.SQalert({content: data.resultMsg,SQ_type: "success"});
	             	   			//查看流程
	             	   			//var params = "?pInsId="+pinstId+"&status="+audStsCd+"&businessKey="+dataId+"&formUrl="+_formUrl;
	             	   			//Add_navTab('tab_cst_invoice_flow_'+dataId+pinstId,'查看流程',"<%=path%>/flow/flow/toFlowShowPageFowBus.do"+params);
	             	   			Remove_navTab();//关闭tab
	             	   			
	             	   		}else{
	             	   			$.ligerDialog.disabledBtns();
	             	   			$.ligerDialog.SQalert({content:"添加失败 , message"+data.resultMsg,SQ_type: "warning"});
	             	   		}
	             	   }
	             	});
                });
            });
        }
    // 添加附件
	function addFileRes(id){
    	$.ligerDialog.open({title: '添加附件信息',height: 300,width: 700, url: '<%=path%>/ass/assSchFee/toAddfileResPage.do?id='+id,
     	   buttons: [{
                 text: "保存", onclick: onSave, type: 'ok', cls: 'l-dialog-btn-ok'
             },
             {
                 text: "取消", onclick: onCancel, type: 'cancel', cls: 'l-dialog-btn-no'
             }
         	]
     	});
    	
    }
	var onSave = function (item, Dialog) {
		 //在子页面里绑定 frameElement.dialog.onOk = function () {}
			if (Dialog.onSave) Dialog.onSave();
		};

	var onCancel = function (item, Dialog) {
		 //在子页面里绑定 frameElement.dialog.onOk = function () {}
			if (Dialog.onCancel) Dialog.onCancel();
	};
	function addFileParam(id ,fileParams){
		//每次添加都需要删除原来的数据
		if(fileParams.length > 2){
			delete docArray[id] ;
			docArray[id] = fileParams ;
		}
		
	}
	</script>
</body>
</html>